package com.niit.notification.service;

import com.niit.notification.entity.Notification;
import com.niit.notification.mapper.NotificationMapper;
import com.niit.notification.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通知服务类
 */
@Service
public class NotificationService {

    @Autowired
    private NotificationMapper notificationMapper;
    
    @Autowired
    private RedisUtil redisUtil;
    
    // 缓存过期时间（秒）
    private static final long CACHE_EXPIRE_TIME = 300;

    /**
     * 获取用户点赞通知
     */
    public List<Map<String, Object>> getLikeNotifications(Long userId, int page, int size) {
        // 构建缓存key
        String cacheKey = "notification:like:" + userId + ":" + page + ":" + size;
        
        // 尝试从缓存获取
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> cachedResult = (List<Map<String, Object>>) redisUtil.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        int offset = (page - 1) * size;
        List<Map<String, Object>> result = notificationMapper.getLikeNotifications(userId, offset, size);
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, result, CACHE_EXPIRE_TIME);
        
        return result;
    }
    
    /**
     * 获取用户点赞通知（使用实体类）
     */
    public List<Notification> getLikeNotificationsEntity(Long userId, int page, int size) {
        // 构建缓存key
        String cacheKey = "notification:like:entity:" + userId + ":" + page + ":" + size;
        
        // 尝试从缓存获取
        @SuppressWarnings("unchecked")
        List<Notification> cachedResult = (List<Notification>) redisUtil.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        int offset = (page - 1) * size;
        List<Notification> result = notificationMapper.getLikeNotificationsEntity(userId, offset, size);
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, result, CACHE_EXPIRE_TIME);
        
        return result;
    }

    /**
     * 获取用户评论通知
     */
    public List<Map<String, Object>> getCommentNotifications(Long userId, int page, int size) {
        // 构建缓存key
        String cacheKey = "notification:comment:" + userId + ":" + page + ":" + size;
        
        // 尝试从缓存获取
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> cachedResult = (List<Map<String, Object>>) redisUtil.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        int offset = (page - 1) * size;
        List<Map<String, Object>> result = notificationMapper.getCommentNotifications(userId, offset, size);
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, result, CACHE_EXPIRE_TIME);
        
        return result;
    }

    /**
     * 获取用户关注通知
     */
    public List<Map<String, Object>> getFollowNotifications(Long userId, int page, int size) {
        // 构建缓存key
        String cacheKey = "notification:follow:" + userId + ":" + page + ":" + size;
        
        // 尝试从缓存获取
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> cachedResult = (List<Map<String, Object>>) redisUtil.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        int offset = (page - 1) * size;
        List<Map<String, Object>> result = notificationMapper.getFollowNotifications(userId, offset, size);
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, result, CACHE_EXPIRE_TIME);
        
        return result;
    }

    /**
     * 获取用户所有通知（合并点赞、评论、关注）
     */
    public List<Map<String, Object>> getAllNotifications(Long userId, int page, int size) {
        // 构建缓存key
        String cacheKey = "notification:all:" + userId + ":" + page + ":" + size;
        
        // 尝试从缓存获取
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> cachedResult = (List<Map<String, Object>>) redisUtil.get(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，获取所有类型的通知
        List<Map<String, Object>> likes = getLikeNotifications(userId, 1, size);
        List<Map<String, Object>> comments = getCommentNotifications(userId, 1, size);
        List<Map<String, Object>> follows = getFollowNotifications(userId, 1, size);
        
        // 合并通知并添加类型标识
        for (Map<String, Object> like : likes) {
            like.put("notification_type", "like");
        }
        
        for (Map<String, Object> comment : comments) {
            comment.put("notification_type", "comment");
        }
        
        for (Map<String, Object> follow : follows) {
            follow.put("notification_type", "follow");
        }
        
        // 合并所有通知
        List<Map<String, Object>> allNotifications = new ArrayList<>();
        allNotifications.addAll(likes);
        allNotifications.addAll(comments);
        allNotifications.addAll(follows);
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, allNotifications, CACHE_EXPIRE_TIME);
        
        return allNotifications;
    }

    /**
     * 获取通知总数
     */
    public int getNotificationCount(Long userId) {
        // 构建缓存key
        String cacheKey = "notification:count:" + userId;
        
        // 尝试从缓存获取
        Object cachedCount = redisUtil.get(cacheKey);
        if (cachedCount != null) {
            return (int) cachedCount;
        }
        
        // 缓存未命中，从数据库查询
        // 获取点赞、评论和关注的总数
        int likeCount = notificationMapper.getLikeNotificationCount(userId);
        int commentCount = notificationMapper.getCommentNotificationCount(userId);
        int followCount = notificationMapper.getFollowNotificationCount(userId);
        
        int totalCount = likeCount + commentCount + followCount;
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, totalCount, CACHE_EXPIRE_TIME);
        
        return totalCount;
    }
    
    /**
     * 清除用户通知缓存
     * 当有新通知产生时调用此方法
     */
    public void clearUserNotificationCache(Long userId) {
        // 清除该用户的所有通知缓存
        String likePattern = "notification:like:" + userId + ":*";
        String commentPattern = "notification:comment:" + userId + ":*";
        String followPattern = "notification:follow:" + userId + ":*";
        String allPattern = "notification:all:" + userId + ":*";
        String countKey = "notification:count:" + userId;
        
        // 这里简化处理，实际应该使用Redis的keys命令查找匹配的key再删除
        // 或者使用Redis的scan命令进行模式匹配删除
        redisUtil.del(countKey);
    }
}
